package com.zlyx.easy.swagger.plugins;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import com.google.common.base.Optional;
import com.zlyx.easy.core.tool.StringFormat;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.swagger.annotations.SpringMapping;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class EasySwaggerOperationSummaryReader implements OperationBuilderPlugin {

	private final DescriptionResolver descriptions;

	@Autowired
	public EasySwaggerOperationSummaryReader(DescriptionResolver descriptions) {
		this.descriptions = descriptions;
	}

	@Override
	public void apply(OperationContext context) {
		Optional<SpringMapping> annotation = context.findAnnotation(SpringMapping.class);
		Optional<ApiOperation> operation = context.findAnnotation(ApiOperation.class);
		String summary = context.getName();
		if (annotation.isPresent() && annotation.get().todo().length > 0) {
			summary = StringFormat.format(annotation.get().todo());
		} else if (operation.isPresent() && StringUtils.isNotEmpty(operation.get().value())) {
			summary = operation.get().value();
		}
		context.operationBuilder().summary(descriptions.resolve(summary));
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return SwaggerPluginSupport.pluginDoesApply(delimiter);
	}
}
